class FoodItemsController < ApplicationController
  
  def index
    @food_items = FoodItem.find(:all)
  end
  
  def edit
    @available_ingredient_types = IngredientType.find(:all)
    @food_item = FoodItem.find(params[:id])
  end
  
  def update
    food_item = FoodItem.find(params[:id])
    food_item.update_attributes(params[:food_item])
    redirect_to :action => "show", :id => params[:id]
    # render :text => params.inspect
  end
  
  def show
    @food_item = FoodItem.find(params[:id])
  end

  def new
    @food_item = FoodItem.new

    respond_to do |format|
      format.html # new.html.erb 
      format.xml  { render :xml => @food_item }
    end
  end
  
  def create
    @food_item = FoodItem.new(params[:food_item])

    respond_to do |format|
      if @food_item.save
        flash[:notice] = 'Food Item was successfully created.'
        format.html { redirect_to(@food_item) }
        format.xml  { render :xml => @food_item, :status => :created, :location => @food_item }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @food_item.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  def add_ingredient
    @food_item = FoodItem.find(params[:id])
    ingredient_type = IngredientType.find(params[:ingredient_type_id].gsub("ingredient_type_", ""))    
    ingredients = @food_item.ingredients
    
    exising_ingredient = ingredients.detect {|ing| ing.ingredient_type == ingredient_type }
    
    if exising_ingredient
      exising_ingredient.quantity += 1
      exising_ingredient.save
    else
      ingredients << Ingredient.create(:ingredient_type => ingredient_type, :quantity => 1)    
    end
    
    render(:update) do |page|
      page.replace_html 'added_ingredients_list', :partial => 'ingredient', :food_item => @food_item
    end
  end
  
  
end